package interceptor;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.ServiceException;

import com.ruoyi.common.core.utils.SpringUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.model.ShopDatabase;
import com.ruoyi.system.api.model.ShopDatabaseProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

public class ShopDataSourceInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(DynamicRoutingDataSource.class);

    private RemoteUserService remoteUserService = SpringUtils.getBean(RemoteUserService.class);


    private DynamicRoutingDataSource dynamicRoutingDataSource = SpringUtils.getBean(DynamicRoutingDataSource.class);

    @Value("${spring.datasource.driverClassName}")
    private String driverClassName;


    private DataSource dataSource = SpringUtils.getBean(DataSource.class);

    private DefaultDataSourceCreator dataSourceCreator = SpringUtils.getBean(DefaultDataSourceCreator.class);;

    private String databaseName;

    public void setDatabaseName(String databaseName) {
        this.databaseName = databaseName;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String url = request.getServletPath();
        //String shopcode = SecurityUtils.getShopId();
        String shopcode= request.getHeader(SecurityConstants.SHOP_ID);
        String databasecode = "";

        if (StringUtils.isNotBlank(shopcode)) {
            R<ShopDatabase> shopDatabaseresult = remoteUserService.getShopDatabaseInfo(shopcode,databaseName, SecurityConstants.INNER);
            if (R.FAIL == shopDatabaseresult.getCode())
            {
                throw new ServiceException(shopDatabaseresult.getMsg());
            }
            ShopDatabase shopDatabase = shopDatabaseresult.getData();
            if(shopDatabase == null || StringUtils.isBlank( shopDatabase.getDatabaseCode()) ){
                throw new RuntimeException(String.format("没有店铺{}数据库{}的连接信息。",shopcode,databaseName));
            }
            databasecode = shopDatabase.getDatabaseCode();

            if( !dynamicRoutingDataSource.getDataSources().keySet().contains(shopDatabaseresult.getData().getDatabaseCode())){
                R<ShopDatabaseProperty> dpresult = remoteUserService.getDatabasePropertyInfo(shopDatabase.getDatabaseCode(), SecurityConstants.INNER);
                if (R.FAIL == shopDatabaseresult.getCode())
                {
                    throw new ServiceException(shopDatabaseresult.getMsg());
                }
                ShopDatabaseProperty dp = dpresult.getData();
                DataSourceProperty dataSourceProperty = new DataSourceProperty();
                BeanUtils.copyProperties(dp,dataSourceProperty);
                DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
                DataSource dataSource = dataSourceCreator.createDataSource(dataSourceProperty);

                ds.addDataSource(databasecode, dataSource);
            }

        }else{
            throw new RuntimeException("缺少店铺信息");
        }

        DynamicDataSourceContextHolder.push(databasecode);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        // 请求结束删除localThread
        DynamicDataSourceContextHolder.poll();
    }
}
